const fs = require("fs");
const multipary = require("multiparty");
const { v4: uuidv4 } = require("uuid");

const STATIC_PATH = "http://154.221.21.109:3005/src/assets/images/";

let loginService = function signInService(params, conn, callback) {
    // 查询 
    // Formidable
    let sql = `SELECT * FROM \`user\` where uPhone='${params.uPhone}' AND uPwd='${params.uPwd}'`;
    console.log(sql);

    conn.query(sql, (err, result) => {
        if (!err) {
            // console.log(result);
            // callback(true);
            console.log('------======-------');
            console.log(result);
            let bol = result && result.length !== 0;

            if (bol) {
                let result_1 = {
                    id: result[0].uid,
                    name: result[0].uName,
                    phone: result[0].uPhone,
                    age: result[0].uAge,
                    sex: result[0].uSex,
                    avatar: result[0].avatar,
                    isLogin: result[0].isLogin,
                };

                // 更新登录状态
                sql = `UPDATE \`user\` SET isLogin=${true} WHERE uid=${result[0].uid}`;
                console.log(sql);

                conn.query(sql, (err, result) => {
                    console.log("%%%%^^^^^^^^^^^^^^^^^^%%%%");

                    if (!err) {
                        console.log("嘻嘻哈哈呵呵");

                        console.log(result);
                        result_1.isLogin = 1;
                        callback(true, result_1);
                    } else {

                        callback(false);
                    }

                });

            } else {
                callback(false);
            }
        } else {
            console.log(err.message);
            callback(false);
        }
    });

};

let logoutService = function signOutService(params, conn, callback) {
    // 删除

    let sql = `DELETE FROM \`user\` WHERE uid=${params.uid}`;
    console.log(sql);

    conn.query(sql, (err, result) => {
        if (!err) {
            console.log(result);
            // callback(true);
            // callback(result);
            if (result.affectedRows) {
                callback(true);
            } else {
                callback(false);
            }
        } else {
            console.log(err.message);
            callback(false);
        }
    });

};

let registerService = function registerService(req, conn, callback) {
    let form = new multipary.Form({ uploadDir: "./src/assets/images" });
    let params = {};
    
   /*  form.on('field', (key, val) => {
        params[key] = val;
    }); */
    
    /* form.on('file', (name, file) => {
        let suffix = file.originalFilename;
        suffix = suffix.substring(suffix.lastIndexOf(".") + 1);
        let filename = `${uuidv4()}.${suffix}`;

        fs.promises.rename(file.path, `./src/assets/images/${filename}`)
            .then(res => {
                console.log('文件名更新成功');
                    // 构建用户头像 url
                    let picUrl = STATIC_PATH + filename;
                    console.log(picUrl);
                    // 构建用户信息对象
                    let obj = {
                        uid: params.userName,
                        uPwd: params.userPwd,
                        uPhone: params.userPhone,
                        uAge: Number(params.userAge) || 12,
                        uSex: Number(params.userSex) || 0,
                        avatar: picUrl,
                    };

                    // 数据库插入操作
                    // 插入
                    let sql = 'INSERT INTO `user`(uName, uPwd, uPhone, uAge, uSex, avatar) VALUES(?,?,?,?,?,?)';
                    let sqlParams = Object.values(obj);
                    conn.query(sql, sqlParams, (err, result) => {
                        if (!err) {

                            console.log(result);
                            callback(true);
                        } else {
                            console.log(err.message);
                            callback(false);
                        }
                    });

            }).catch(err => {
                console.log('文件名更新失败');
                console.log(err.message);
            });
    }); */


    

    form.parse(req, function (err, fields, files) {
        if (!err) {
            console.log(';;;;;;');
            let suffix = file.originalFilename;
            suffix = suffix.substring(suffix.lastIndexOf(".") + 1);
            let filename = `${uuidv4()}.${suffix}`;
            console.log(fields);
            console.log(files);
            
            
            // fs.promises.rename(file.path, `./src/assets/images/${filename}`)
            //     .then(res => {
            //         console.log('文件名更新成功');
            //             // 构建用户头像 url
            //             let picUrl = STATIC_PATH + filename;
            //             console.log(picUrl);
            //             // 构建用户信息对象
            //             let obj = {
            //                 uid: fields.userName[0],
            //                 uPwd: fields.userPwd[0],
            //                 uPhone: fields.userPhone[0],
            //                 uAge: Number(fields.userAge[0]) || 12,
            //                 uSex: Number(fields.userSex[0]) || 0,
            //                 avatar: picUrl,
            //             };
    
            //             // 数据库插入操作
            //             // 插入
            //             let sql = 'INSERT INTO `user`(uName, uPwd, uPhone, uAge, uSex, avatar) VALUES(?,?,?,?,?,?)';
            //             let sqlParams = Object.values(obj);
            //             conn.query(sql, sqlParams, (err, result) => {
            //                 if (!err) {
    
            //                     console.log(result);
            //                     callback(true);
            //                 } else {
            //                     console.log(err.message);
            //                     callback(false);
            //                 }
            //             });
    
            //     }).catch(err => {
            //         console.log('文件名更新失败');
            //         console.log(err.message);
            //     });
           
        } else {
            console.log(err.message);
        }
    });



};

let isLxUserService = function isLxUserService(params, conn, callback) {
    // 查询

    let sql = `SELECT * FROM \`user\` where uPhone='${params.uPhone}'`;
    console.log(sql);

    conn.query(sql, (err, result) => {
        if (!err) {
            console.log("*********************");

            console.log(result);
            // callback(true);
            callback(result && result.length !== 0 ? true : false);
        } else {
            console.log(err.message);
            // callback(false);
        }
    });

};

module.exports = {
    loginService,
    logoutService,
    registerService,
    isLxUserService,
};